package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Services.ResourceService;
import com.example.demo.Services.UserService;
import com.example.demo.ShiroConfig.CustomeToken;
import com.example.demo.ShiroConfig.LoginType;
import com.example.demo.entity.User;
import com.example.demo.entity.resource;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.sun.xml.internal.bind.v2.runtime.output.SAXOutput;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.WebParam;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Security;
import java.util.*;

/**
 * ClassName:IndexController
 * Package:com.controller
 * Description:
 *
 * @date:2019/12/12 15:41
 * @author:
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {

    @Autowired
    UserService userService;

    @Autowired
    ResourceService resourceService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping(value = "toindex")
    public String login(Model model){
        model.addAttribute("name","Jonou");
        return "index";
    }

    @RequestMapping(value = "tologin")
    public String tologin(Model model){

        return "tologin";
    }

    @RequestMapping(value = "user/add")
    public String addUser(Model model){
        return "user/adduser";
    }

    @RequestMapping(value = "user/update")
    public String updateUser(Model model){
        return "user/updateuser";
    }

    @RequestMapping(value = "toError")
    public String error(Model model){
        model.addAttribute("msg","没有权限");
        return "error";
    }


    @RequestMapping(value = "login")
    public String index(String name,String password,Model model){
        /**
         * 使用shiro 的认证功能
         */
        Subject subject = SecurityUtils.getSubject();


        CustomeToken token = new CustomeToken(name,password, LoginType.PASSWORD);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
//            e.printStackTrace();
            model.addAttribute("msg","用户名不存在");
            return "tologin";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "tologin";
        }
        return "redirect:toindex";
    }

    @RequestMapping(value = "loginNoPwd")
    public String indexNoPwd(String name,Model model){
        /**
         * 使用shiro 的认证功能
         */
        System.out.println(name);
        Subject subject = SecurityUtils.getSubject();


        CustomeToken token = new CustomeToken(name, LoginType.NOPASSWD);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
//            e.printStackTrace();
            model.addAttribute("msg","用户名不存在");
            return "tologin";
        }
        return "redirect:toindex";
    }

    @RequestMapping(value = "logout")
    public String logout(HttpSession session, Model model){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","登出成功");
        return "tologin";
    }


    /**
     * MybatisPlus 方法测试
     * @param id
     * @return
     */
    @RequestMapping("getInfo")
    public String getInfo(Integer id,Model model){
        User userInfo = userService.getById(id);
        model.addAttribute("user",userInfo);
        return "user";
    }

    /**
     * 获取全部用户信息
     * @param userId
     * @return
     */
    @PostMapping("getList")
    public List<User> getList(@RequestBody String userId){
        List<User> userList = userService.list();
        return userList;
    }

    /**
     * 分页查询所有数据
     */
    @PostMapping("getInfoListPage")
    public IPage<User> getInfoListPage(){
        //需要在Config配置类中配置分页插件
        IPage<User> page = new Page<>();
        page.setCurrent(1); //当前页
        page.setSize(3);    //每页条数
        page = userService.page(page);
        return page;
    }


    /**
     * 根据指定字段查询用户信息集合
     * @return
     */
    @PostMapping("getListMap")
    public Collection<User> getListMap(){
        Map<String,Object> map = new HashMap<>();
        //kay是字段名 value是字段值
        map.put("age",20);
        Collection<User> UserList = userService.listByMap(map);
        return UserList;
    }


    /**批量新增用户信息
     *
     */
    @PostMapping("saveInfoList")
    public void saveInfoList(){
        //创建对象   这是一个例子，到时候根据实际情况添加
//        User sans = new User();
//        sans.setName("Sans");
//        sans.setSkill("睡觉");
//        sans.setAge(18);
//        sans.setFraction(60L);
//        sans.setEvaluate("Sans是一个爱睡觉,并且身材较矮骨骼巨大的骷髅小胖子");
//        User papyrus = new User();
//        papyrus.setName("papyrus");
//        papyrus.setSkill("JAVA");
//        papyrus.setAge(18);
//        papyrus.setFraction(58L);
//        papyrus.setEvaluate("Papyrus是一个讲话大声、个性张扬的骷髅，给人自信、有魅力的骷髅小瘦子");
//        //批量保存
//        List<User> list =new ArrayList<>();
//        list.add(sans);
//        list.add(papyrus);
//        UserService.saveBatch(list);
    }

    @RequestMapping("tozTree")
    public String toZtree(){
        return "zTree";
    }

    @ResponseBody
    @RequestMapping("findMenu")
    public List<resource> findMenu(Model model, HttpServletRequest request){
        String mykey = request.getParameter("key");
//        List<resource>resList =  resourceService.findBykey(mykey);
        List<resource>resList =  resourceService.findAll();
//        model.addAttribute("res",resList);
        System.out.println(resList);
        return resList;
    }


    @RequestMapping("findMenuBtn")
    public String findMenuBtn(Model model,String key, HttpServletRequest request){
        String mykey = request.getParameter("key");
        List<resource>resList =  resourceService.findBykey(key);
//        List<resource>resList =  resourceService.findAll();
        model.addAttribute("res",resList);
        System.out.println(resList);
        return "btn";
    }


    //表单验证
    @RequestMapping("toFrom")
    public String toFrom(){
        return "form";
    }

    @RequestMapping("ValidateUserName")
    @ResponseBody
    public String ValidateUserName(String username){
        System.out.println(username);
        User userInfo = userService.findByname(username);
        if(userInfo==null){
            return "true";
        }
        return "false";
    }


    /**
     * redis缓存测试
     */
    @RequestMapping("setRedis")
    public String sayHello(Model model){
        redisTemplate.opsForValue().set("hello","world");
        model.addAttribute("success","success");
        return "redis";
    }

    @RequestMapping("getRedis")
    public String getRedis(Model model){
        Set<String> data = redisTemplate.opsForSet().members("UserList");

       if(data==null){
           Map<String,Object> map = new HashMap<>();
           //kay是字段名 value是字段值
           map.put("userStatus",1);
           List<User> UserList =  (List<User>) userService.listByMap(map);
           if(UserList==null){
               redisTemplate.opsForSet().add("UserList","null");
           }else{
               System.out.println("===========>" + UserList.get(0).toString());
               redisTemplate.opsForSet().add("UserList",UserList.toString());
           }
           model.addAttribute("getRedis",UserList);
           model.addAttribute("is","数据库的值");
       }else{
           model.addAttribute("getRedis",data);
           model.addAttribute("is","缓存的值");
       }


        return "redis";
    }

}

